package com.sakura.二叉树;

import java.util.HashMap;

public class Code105_从前序与中序遍历序列构造二叉树 {

    // Definition for a binary tree node.
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    HashMap<Integer, Integer> map = new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        for (int i = 0; i < inorder.length; i++)
            map.put(inorder[i], i);

        return buildHelp(inorder, 0, inorder.length, preorder, 0, preorder.length);
    }

    private TreeNode buildHelp(int[] inorder, int inStart, int inEnd, int[] preorder, int preStart, int preEnd) {
        if (inStart >= inEnd || preStart >= preEnd) {
            return null;
        }
        int rootVal = preorder[preStart];
        TreeNode root = new TreeNode(rootVal);
        // 分隔
        int rootIndex = map.get(rootVal);
        int leftSize = rootIndex - inStart;
        root.left = buildHelp(inorder, inStart, rootIndex, preorder, preStart + 1, preStart + leftSize + 1);
        root.right = buildHelp(inorder, rootIndex + 1, inEnd, preorder, preStart + leftSize + 1, preEnd);
        return root;
    }
}
